package com.hgb.mall.portal.services.impl;

import cn.hutool.core.collection.CollUtil;
import com.hgb.mall.common.exception.ApiException;
import com.hgb.mall.mbg.entity.OmsCartItem;
import com.hgb.mall.mbg.entity.UmsMember;
import com.hgb.mall.mbg.mapper.OmsCartItemDynamicSqlSupport;
import com.hgb.mall.mbg.mapper.OmsCartItemMapper;
import com.hgb.mall.portal.dao.PortalProductDao;
import com.hgb.mall.portal.domain.CartProduct;
import com.hgb.mall.portal.domain.CartPromotionItem;
import com.hgb.mall.portal.services.OmsCartItemService;
import com.hgb.mall.portal.services.OmsPromotionService;
import com.hgb.mall.portal.services.UmsMemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import static org.mybatis.dynamic.sql.SqlBuilder.*;

/**
 * 购物车管理Service实现类
 * Created by hgb on 2020/8/2.
 */
@Service
public class OmsCartItemServiceImpl implements OmsCartItemService {
    @Autowired
    private OmsCartItemMapper cartItemMapper;
    @Autowired
    private PortalProductDao productDao;
    @Autowired
    private OmsPromotionService promotionService;
    @Autowired
    private UmsMemberService memberService;

    @Override
    public int add(OmsCartItem cartItem) {
        int count;
        UmsMember currentMember = memberService.getCurrentMember();
        cartItem.setMemberId(currentMember.getId());
        cartItem.setMemberNickname(currentMember.getNickname());
        cartItem.setDeleteStatus(0);
        OmsCartItem existCartItem = getCartItem(cartItem);
        if (existCartItem == null) {
            cartItem.setCreateDate(new Date());
            count = cartItemMapper.insert(cartItem);
        } else {
            cartItem.setModifyDate(new Date());
            existCartItem.setQuantity(existCartItem.getQuantity() + cartItem.getQuantity());
            count = cartItemMapper.updateByPrimaryKey(existCartItem);
        }
        return count;
    }

    @Override
    public long addIgnoreExist(OmsCartItem cartItem) {
        UmsMember currentMember = memberService.getCurrentMember();
        cartItem.setMemberId(currentMember.getId());
        cartItem.setMemberNickname(currentMember.getNickname());
        cartItem.setDeleteStatus(0);
        cartItem.setCreateDate(new Date());
        cartItemMapper.insert(cartItem);
        return cartItemMapper.selectOne(c ->
                c.orderBy(OmsCartItemDynamicSqlSupport.id.descending()).limit(1))
                             .map(OmsCartItem::getId).orElseThrow(() -> new ApiException("生成失败"));
    }

    /**
     * 根据会员id,商品id和规格获取购物车中商品
     */
    private OmsCartItem getCartItem(OmsCartItem cartItem) {

        List<OmsCartItem> cartItemList = cartItemMapper.select(c -> c
                .where(OmsCartItemDynamicSqlSupport.memberId, isEqualTo(cartItem.getMemberId()))
                .and(OmsCartItemDynamicSqlSupport.productId, isEqualTo(cartItem.getProductId()))
                .and(OmsCartItemDynamicSqlSupport.deleteStatus, isEqualTo(0))
                .and(OmsCartItemDynamicSqlSupport.productSkuId, isEqualToWhenPresent(cartItem.getProductSkuId()))
        );
        if (!CollectionUtils.isEmpty(cartItemList)) {
            return cartItemList.get(0);
        }
        return null;
    }

    @Override
    public List<OmsCartItem> list(Long memberId) {
        return cartItemMapper.select(c -> c
                .where(OmsCartItemDynamicSqlSupport.deleteStatus, isEqualTo(0))
                .and(OmsCartItemDynamicSqlSupport.memberId, isEqualTo(memberId))
                .orderBy(OmsCartItemDynamicSqlSupport.id.descending())
        );
    }

    @Override
    public List<CartPromotionItem> listPromotion(Long memberId, List<Long> cartIds) {
        List<OmsCartItem> cartItemList = list(memberId);
        if (CollUtil.isNotEmpty(cartIds)) {
            cartItemList = cartItemList.stream().filter(item -> cartIds.contains(item.getId()))
                                       .collect(Collectors.toList());
        }
        List<CartPromotionItem> cartPromotionItemList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(cartItemList)) {
            cartPromotionItemList = promotionService.calcCartPromotion(cartItemList);
        }
        return cartPromotionItemList;
    }

    @Override
    public int updateQuantity(Long id, Long memberId, Integer quantity) {
        return cartItemMapper.update(c -> c
                .set(OmsCartItemDynamicSqlSupport.quantity).equalTo(quantity)
                .where(OmsCartItemDynamicSqlSupport.deleteStatus, isEqualTo(0))
                .and(OmsCartItemDynamicSqlSupport.id, isEqualTo(id))
                .and(OmsCartItemDynamicSqlSupport.memberId, isEqualTo(memberId))
        );
    }

    @Override
    public int delete(Long memberId, List<Long> ids) {
        return cartItemMapper.update(c -> c
                .set(OmsCartItemDynamicSqlSupport.deleteStatus).equalTo(1)
                .where(OmsCartItemDynamicSqlSupport.id, isIn(ids))
                .and(OmsCartItemDynamicSqlSupport.memberId, isEqualTo(memberId))
        );
    }

    @Override
    public CartProduct getCartProduct(Long productId) {
        return productDao.getCartProduct(productId);
    }

    @Override
    public int updateAttr(OmsCartItem cartItem) {
        //删除原购物车信息
        OmsCartItem updateCart = new OmsCartItem();
        updateCart.setId(cartItem.getId());
        updateCart.setModifyDate(new Date());
        updateCart.setDeleteStatus(1);
        cartItemMapper.updateByPrimaryKeySelective(updateCart);
        cartItem.setId(null);
        add(cartItem);
        return 1;
    }

    @Override
    public int clear(Long memberId) {
        return cartItemMapper.update(c -> c
                .set(OmsCartItemDynamicSqlSupport.deleteStatus).equalTo(1)
                .where(OmsCartItemDynamicSqlSupport.memberId, isEqualTo(memberId))
        );
    }
}
